const express = require('express');
const router = express.Router();
const db = require('../config/database');

// 获取字体样式分类列表
router.get('/', async (req, res) => {
  try {
    const { populate } = req.query;
    
    let query = `
      SELECT 
        fst.id,
        fst.name,
        fst.description,
        fst.sort_order,
        fst.created_at,
        fst.updated_at
    `;
    
    if (populate === '*') {
      query += `,
        COUNT(fs.id) as font_style_count
      FROM font_style_types fst
      LEFT JOIN font_styles fs ON fst.id = fs.type_id
      GROUP BY fst.id
      ORDER BY fst.sort_order ASC, fst.created_at DESC
      `;
    } else {
      query += `
      FROM font_style_types fst
      ORDER BY fst.sort_order ASC, fst.created_at DESC
      `;
    }
    
    const [rows] = await db.execute(query);
    
    const data = rows.map(row => ({
      id: row.id,
      attributes: {
        name: row.name,
        description: row.description,
        sort_order: row.sort_order,
        createdAt: row.created_at,
        updatedAt: row.updated_at,
        ...(populate === '*' && {
          font_style_count: row.font_style_count || 0
        })
      }
    }));
    
    res.json({ data });
  } catch (error) {
    console.error('获取字体样式分类失败:', error);
    res.status(500).json({ error: '获取字体样式分类失败' });
  }
});

module.exports = router;